//comment.js
const db = wx.cloud.database()
var app = getApp();
Page({

  data: {
    tasks: [],
    isMyTask: false,
    isAchieve: false,
  },

  onLoad: function (options) {
    let that = this;
    console.log(that.data.isAchieve)
    var taskId = getApp().requestDetailid;
    const db = wx.cloud.database()
    db.collection("tasks").where({
      _id: taskId
    }).get({
      success: res => {
        that.setData({
          tasks: res.data,
        })
        console.log(res.data)
        if (that.data.tasks[0].isAchieve == 0) {
          that.setData({
            isAchieve: false
          })
          console.log(that.data.isAchieve)
        } else {
          that.setData({
            isAchieve: true
          })
          console.log(that.data.isAchieve)
        }
        try {
          // 同步接口立即返回值
          var localusername = wx.getStorageSync('localusername')
          console.log(localusername)
          if (that.data.tasks[0].accepter == localusername) {
            that.setData({
              isMyTask: true
            })
            console.log(that.data.isMyTask)
          } else {
            that.setData({
              isMyTask: false
            })
            console.log(that.data.isMyTask)
          }
        } catch (e) {
          console.log('读取发生错误')
        }
      },
      fail: err => {
        wx.showToast({
          icon: "none",
          title: '加载失败',
        })
      }
    })

  },

  // 揭榜
  acceptTask: function (event) {
    var taskId = event.currentTarget.dataset.taskid;
    console.log(taskId)
    db.collection("tasks").where({
      _id: taskId
    }).update({
      data: {
        isAccept: 1,
      },
    }).then(res => {
      console.log(res)
      wx.showToast({
        icon: "none",
        title: '揭榜成功',
      })
    })
  },

  //完成任务
  achieveTask: function (event) {
    var taskId = event.currentTarget.dataset.taskid;
    console.log(taskId)
    db.collection("tasks").where({
      _id: taskId
    }).update({
      data: {
        isAchieve: 1,
      },
    }).then(res => {
      console.log(res)
      this.setData({
        isAchieve: true
      })
      wx.showToast({
        icon: "none",
        title: '已完成任务！',
      })
    })
  }
})